/**
 * @File name : LoginController.java
 * @Description :
 * @Creator : haifeng17
 * @CreateTime : Mar 9, 2017 10:54:11 AM
 * @Version : 1.0
 * @Update records:
 *         1.1 Mar 9, 2017 by haifeng17:
 *         1.0 Mar 9, 2017 by haifeng17: Created
 *         All rights served : XXX CORP.
 */
package com.ent.app.bms.web.controller.system;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ent.app.bms.bean.SysUser;
import com.ent.app.bms.service.system.UserService;
import com.ent.app.bms.util.Const;
import com.ent.app.bms.util.DateOperator;
import com.ent.app.bms.util.EndecryptUtils;
import com.ent.app.bms.web.controller.base.BaseController;
import com.ent.app.common.util.PageData;
import com.ent.app.common.util.Tools;

@Controller
public class LoginController extends BaseController {

    @Resource(name = "userService")
    private UserService userService;

    @RequestMapping(value = "/register", method = { RequestMethod.POST })
    @ResponseBody
    public Object register(@RequestBody SysUser user) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        //密码加密
        Map<String, String> credentialMap = EndecryptUtils.encryptMD5(user.getUsername(), user.getPassword());
        user.setPassword(credentialMap.get("pwd"));
        user.setSalt(credentialMap.get("salt"));
        user.setUserStatus((byte) 0);
        //FIXME: 时间取不到时分秒，可能需要修改列类型
        user.setCreateTime(DateOperator.convertStringToDate(DateOperator.getDateTime()));
        user.setIsLock(false);
        String reslut = "";
        try {
            reslut = userService.saveUser(user) == 1 ? "success" : "fail";
        } catch (Exception e) {
            reslut = "fail";
            logger.debug(e.getMessage());
        }
        logger.debug(reslut);
        data.put("result", reslut);
        return data;
    }

    /**
     * 登录到主页
     * @Description :用户点击登录后，验证完用户名密码后调用此方法，获取权限信息并跳转到主页 
     * @Param : 
     * @Return :ModelAndView 
     * @CreateTime : Mar 29, 2017 2:42:55 PM
     * @Updator : 
     * @UpdateTime :
     */
    @RequestMapping(value = "/login_toMain")
    public ModelAndView login_toMain() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
        mv.setViewName("system/index/main");
        mv.addObject("pd", pd);
        return mv;
    }

    @RequestMapping(value = "/login_toRegister")
    public ModelAndView login_toRegister() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        //pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
        mv.setViewName("system/index/sign-up");
        mv.addObject("pd", pd);
        return mv;
    }

    @RequestMapping(value = "/login_toLogin")
    public ModelAndView toLogin() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
        mv.setViewName("system/index/login");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 登录
     * @Description :点击登录按钮，验证用户名、密码 
     * @Param : 
     * @Return : Map<String, String>
     * @CreateTime : Mar 29, 2017 2:44:47 PM
     * @Updator : 
     * @UpdateTime :
     */
    @RequestMapping(value = "/login", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object login(@RequestBody SysUser user) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        String result = "";
        if (user != null) {
            //前台输入的用户名
            String username = user.getUsername();
            //前台输入的密码
            String password = user.getPassword();
            boolean isRememberMe = user.isRememberMe();
            logger.debug("username-{}, password-{}, isRememberMe-{}", username, password, isRememberMe);
            //Shiro方式获取角色权限信息
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password, isRememberMe);
            try {
                subject.login(token);
                if (subject.isAuthenticated()) {
                    logger.debug("{}-登录成功", username);
                    result = "success";
                }
                //检查是否有默认角色
                //subject.checkRole("default_role");
                //检查是否有访问首页的权限
                subject.checkPermission("index:view");
            } catch (IncorrectCredentialsException e) {
                result = "username-or-pwd-error";
                logger.debug("登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.");
            } catch (ExcessiveAttemptsException e) {
                result = "login-failed-so-much-times";
                logger.debug("登录失败次数过多");
            } catch (LockedAccountException e) {
                result = "account-locked";
                logger.debug("帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.");
            } catch (DisabledAccountException e) {
                result = "account-disabled";
                logger.debug("帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.");
            } catch (ExpiredCredentialsException e) {
                result = "account-expired";
                logger.debug("帐号已过期. the account for username " + token.getPrincipal() + "  was expired.");
            } catch (UnknownAccountException e) {
                result = "account-not-exists";
                logger.debug("帐号不存在. There is no user with username of " + token.getPrincipal());
            } catch (UnauthorizedException e) {
                result = "no-permission";
                logger.debug("您没有得到相应的授权！" + e.getMessage());
            }
        } else {
            result = "param-tran-error";
            logger.debug("参数传递错误");
        }
        data.put("result", result);
        return data;
    }
}
